<template>
  <div class="container">
    <div id="map"></div>
  </div>
</template>

<script>
import "mapbox-gl/dist/mapbox-gl.css";
import mapboxgl from "mapbox-gl";
import {
  genetorGeoJosn,
  drawCanvas,
  genetorData,
} from "../../src/utils/dataUtils";
export default {
  name: "Vue2MapboxMapTemplate ",
  data() {
    return {};
  },

  mounted() {
    this.initMap();

  },

  methods: {
    initMap() {
      mapboxgl.accessToken =
        "pk.eyJ1IjoiY3Vpaml5aW5nIiwiYSI6ImNsZ3QyZjY4ODAxbDEza3BkOTJqbTJvN3gifQ.Ldj9qAFzb5uzcLP-VtFB3A";
      this.map = new mapboxgl.Map({
        container: "map", // container ID
        style: "mapbox://styles/cuijiying/cll09l2nz007w01picbmj3e1z", // style URL
        center: [118.601604, 31.905137], // starting position [lng, lat]
        zoom: 10, // starting zoom
        projection: "mercator",
      });

      this.jsonData = genetorGeoJosn(
        {
          ymax: 41.072443,
          ymin: 25.905137,
          xmax: 121.601604,
          xmin: 100.495696,
        },
        2000
      );

      // load事件
      this.map.on("load", async () => {

      const imageDatas = [{
        id: 'rect-canvas-q',
        path: './icons/晴天.png'
        },
        {
          id: 'rect-canvas-y',
          path: './icons/阴天.png'
        }
      ]

      const promises = []
      imageDatas.forEach((item)=>{
        promises.push(this.loadImage(item.id, item.path))
      })

      const resP = await Promise.all(promises)


      

      if(resP){
        console.log(resP, 'res==============');
        console.log(this.map.hasImage('rect-canvas-q'), );
      }

        this.map.addSource("points", {
          type: "geojson",
          data: this.jsonData,
        });

        this.map.addLayer({
          id: "points",
          type: "symbol",
          source: "points",
          layout: {
            // "icon-image": "star",
            "icon-image": [
              "match",
              ["get", "type"], // 替换为您的属性字段名
              0,
              "rect-canvas-q", 
              "rect-canvas-y", // 默认图标名称
            ],
            "text-field": "{name}",
          },
          paint: {
            'text-color': '#fff'
          }
        });



      });

      // this.map.on("click", "points", function (e) {
      //   const feature = e.features[0];
      //   const title = e.features[0].properties.type;
      //   console.log(feature, title);
      // });

    },

    loadImage(iconId, url) {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        // 绘制矩形
        canvas.width = 150;
        canvas.height = 50;
        const width = 130;
        const height = 40;
        const cornerRadius = 10;
        const offset = 5;
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.src = url;
            img.onload = () => {
                // resolve(img);
  

                ctx.beginPath();
                ctx.moveTo(cornerRadius, offset);
                ctx.lineTo(width - cornerRadius, offset);
                ctx.arcTo(width, offset, width, cornerRadius, cornerRadius);
                ctx.lineTo(width, height - cornerRadius);
                ctx.arcTo(width, height, width - cornerRadius, height, cornerRadius);
                ctx.lineTo(cornerRadius, height);
                ctx.arcTo(offset, height, offset, height - cornerRadius, cornerRadius);
                ctx.lineTo(offset, cornerRadius);
                ctx.arcTo(offset, offset, cornerRadius, offset, cornerRadius);

                // 添加阴影效果
                // 需要画布大小要大于图层大小，否则阴影会被截掉看不到阴影效果
                ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
                ctx.shadowBlur = 3;

                ctx.fillStyle = 'white';
                ctx.fill();


                // 内部矩形圆角
                const innerWidth = 80;
                const innerX = width - innerWidth + cornerRadius;
                ctx.beginPath();
                ctx.moveTo(innerX, offset);
                ctx.lineTo(width - cornerRadius, offset);
                ctx.arcTo(width, offset, width, cornerRadius, cornerRadius);

                ctx.lineTo(width, height - cornerRadius);
                ctx.arcTo(width, height, width - cornerRadius, height, cornerRadius);

                ctx.lineTo(innerX, height);
                ctx.arcTo(innerX-cornerRadius, height, innerX-cornerRadius, height - cornerRadius, cornerRadius);
                
                ctx.lineTo(innerX-cornerRadius, cornerRadius);
                ctx.arcTo(innerX-cornerRadius, offset, innerX, offset, cornerRadius);

                ctx.fillStyle = 'lightblue';
                ctx.fill();


                ctx.drawImage(img, 10, 15, 30, 30);
                // console.log(context.getImageData(0,0,150,50).data, 'ddddddddddddddddddddd');
                // !this.map.hasImage(iconId) && this.map.addImage(iconId, {with: 150, height: 50, data: context.getImageData(0,0,150,50).data});
                // !this.map.hasImage(iconId) && this.map.addImage(iconId, img);

                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                const newImageData = new ImageData(imageData.data, imageData.width, imageData.height);
                !this.map.hasImage(iconId) && this.map.addImage(iconId, newImageData);
                resolve('loaded');
            };
            img.onerror = (error) => {
                reject(error);
            };
        });
    },


    loadIcon(iconId) {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        // 绘制矩形
        canvas.width = 150;
        canvas.height = 50;

        context.fillStyle = "rgba(255, 0, 0, 255)"; // 设置填充颜色为白色
        context.fillRect(0, 0, canvas.width, canvas.height);
        console.log(context.getImageData(0,0,150,50).data, 'ddddddddddddddddddddd');
        // !this.map.hasImage(iconId) && this.map.addImage(iconId, {with: 150, height: 50, data: context.getImageData(0,0, 150, 50).data});
        const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        const newImageData = new ImageData(imageData.data, imageData.width, imageData.height);
        !this.map.hasImage(iconId) && this.map.addImage(iconId, newImageData);
    }

  },
};
</script>

<style>
.join-btn{
  position: absolute;
  top: 20px;
  left: 50px;
}
</style>
